package com.ll.menu.user.cart;


import com.ll.menu.user.app.entity.Food;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

/**
 * 购物车管理
 *
 * @author wangheng
 */
public class CartManager {

    private ArrayList<Food> mList = new ArrayList<>();

    private CartManager() {

    }

    private static class SingletonInstance {
        private static final CartManager INSTANCE = new CartManager();
    }

    public static CartManager getInstance() {
        return SingletonInstance.INSTANCE;
    }

    public void clearCart(){
        mList.clear();
        EventBus.getDefault().post(CartEvent.createEvent(CartEvent.TYPE_CLEAR_FOOD_LIST));
    }

    public void addFood(Food food){
        if(food == null){
            return;
        }
        mList.add(food);
        EventBus.getDefault().post(CartEvent.createEvent(CartEvent.TYPE_ADD_FOOD));
    }

    public void removeFood(Food food){
        mList.remove(food);
        EventBus.getDefault().post(CartEvent.createEvent(CartEvent.TYPE_REMOVE_FOOD));
    }

    public void removeFoodById(String id){
        if(id == null){
            return;
        }
        Food target = null;
        for(Food food : mList ){
            if(food != null && id.equals(food.getId())){
                target = food;
                break;
            }
        }
        mList.remove(target);
        EventBus.getDefault().post(CartEvent.createEvent(CartEvent.TYPE_REMOVE_FOOD));
    }

    public ArrayList<Food> getFoodList(){
        return mList;
    }

    public void appendFoodListToCart(ArrayList<Food> list){
        if(list == null || list.size() == 0){
            return;
        }
        mList.addAll(list);
        EventBus.getDefault().post(CartEvent.createEvent(CartEvent.TYPE_APPEND_FOOD_LIST));
    }

    public void resetFoodList(ArrayList<Food> list){
        if(list == null || list.size() == 0){
            return;
        }
        mList.clear();
        mList.addAll(list);
        EventBus.getDefault().post(CartEvent.createEvent(CartEvent.TYPE_REPLACE_FOOD_LIST));
    }

    public int getFoodTotalCount(){
        int total = 0;
        for(Food food : mList){
            total += food.getCount();
        }
        return total;
    }

    public float getTotalPrice(){
        float price = 0;
        for(Food food : mList){
            price += food.getCurrentPrice() * food.getCount();
        }
        return price;
    }

}